package core.db.h2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.h2.tools.Server;

public class H2BaseDaoTemplate {
	
	private Server server;
	private String port = "9080";
	private String dbDir = "jdbc:h2:./h2db/sample";
	private String user = "sa";
	private String password = "";
	
	public void startServer() {
		try {
			System.out.println("正在启动h2...");
			server = Server.createTcpServer(new String[] { "-tcpPort", port })
					.start();
		} catch (SQLException e) {
			System.out.println("启动h2出错：" + e.toString());
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}	
	
	
	public boolean execute(String sql) {
		boolean flag=true;
		try {
			Class.forName("org.h2.Driver");
			Connection conn = DriverManager.getConnection(dbDir,user, password);
			Statement stat = conn.createStatement();
			stat.execute(sql);	
			stat.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
			flag=false;
		} finally {
		}
		return flag;
	}
	
	public List<Map<String, Object>> query(String sql) {
		List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
		try {
			Class.forName("org.h2.Driver");
			Connection conn = DriverManager.getConnection("jdbc:h2:" + dbDir,user, password);
			Statement stat = conn.createStatement();
			ResultSet result = stat.executeQuery(sql);
			ResultSetMetaData rsmd=result.getMetaData();
			List<String> columns=new ArrayList<String>();
			for(int ik=1;ik<=rsmd.getColumnCount();ik++)
			{
				String columnName=rsmd.getColumnName(ik);
				columns.add(columnName);
			}
			while(result.next()) {
				Map<String,Object> map=new HashMap<String, Object>();
				for(String column:columns) {
//					Object vvvv=rSet.getObject(column);
//					if((vvvv!=null) && (vvvv) instanceof Date) {
//						vvvv=vvvv+"";
//					}
//					map.put(column, vvvv);
					map.put(column, result.getString(column));
				}
				list.add(map);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return list;
	}
	
	
}
